<template>
  <div class="tree-transfer-container">
    <a-transfer
      v-model:target-keys="targetKeys"
      :data-source="flattenedData"
      :render="renderItem"
      :show-select-all="false"
      :list-style="{ width: '400px', height: '500px' }"
      class="custom-transfer"
      @change="handleTransferChange"
      :selected-keys="checkedKeys"
    >
      <template #children="{ direction, onItemSelect }">
        <template v-if="direction === 'left'">
          <a-tree
            checkable
            :tree-data="treeData"
            :checked-keys="combinedCheckedKeys"
            :check-strictly="false"
            default-expand-all
            @check="handleTreeCheck"
          />
        </template>
        <template v-else>
          <draggable
            v-model="sortedTargetKeys"
            :animation="300"
            @end="handleDragEnd"
            class="right-panel"
          >
            <template #item="{ element: key }">
              <div class="right-item">
                <span class="item-content">{{ getDisplayText(key) }}</span>
                <a-button
                  :type="buttonStates[key] ? 'primary' : 'default'"
                  size="small"
                  @click.stop="handleButtonClick(key)"
                >
                  {{ buttonStates[key] ? '已激活' : '激活' }}
                </a-button>
              </div>
            </template>
          </draggable>
        </template>
      </template>
    </a-transfer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { Tree, Transfer, Button } from 'ant-design-vue';
import draggable from 'vuedraggable';
import type { Key } from 'ant-design-vue/es/_util/type';
import type { TransferItem, TransferProps } from 'ant-design-vue/es/transfer';
import type { TreeProps } from 'ant-design-vue/es/tree';

// 1. 核心类型定义
type CheckedKeys = Key[] | { checked: Key[]; halfChecked: Key[] };

interface TreeNode {
  key: string;
  title: string;
  children?: TreeNode[];
  parentKey?: string;
  isLeaf: boolean;
  disabled?: boolean;
}

// 2. 原始数据
const treeData: TreeNode[] = [
  {
    key: '1',
    title: '产品管理',
    isLeaf: false,
    children: [
      { key: '1-1', title: '产品列表', parentKey: '1', isLeaf: true },
      { key: '1-2', title: '分类管理', parentKey: '1', isLeaf: true },
    ]
  },
  {
    key: '2',
    title: '订单管理',
    isLeaf: false,
    children: [
      { key: '2-1', title: '订单列表', parentKey: '2', isLeaf: true },
    ]
  },
  { key: '3', title: '系统设置', isLeaf: true },
];

// 3. 扁平化数据源
const flattenedData = ref<TransferItem[]>([]);

const flattenTree = (nodes: TreeNode[]): TransferItem[] => {
  const result: TransferItem[] = [];
  nodes.forEach(node => {
    if (node.isLeaf) {
      result.push({
        key: node.key,
        title: node.title,
        disabled: node.disabled,
        attrs: { parentKey: node.parentKey }
      });
    }
    if (node.children?.length) {
      result.push(...flattenTree(node.children));
    }
  });
  return result;
};

flattenedData.value = flattenTree(treeData);

// 4. 响应式状态
const targetKeys = ref<string[]>([]);
const checkedKeys = ref<string[]>([]);

const combinedCheckedKeys = computed<string[]>(() => [
  ...checkedKeys.value,
  ...targetKeys.value
]);

const sortedTargetKeys = computed<string[]>({
  get: () => [...targetKeys.value],
  set: (newKeys) => { targetKeys.value = newKeys; }
});

const buttonStates = ref<Record<string, boolean>>({});

// 5. 渲染函数
const renderItem: TransferProps['render'] = (item) => {
  return item.title ?? '';
};

// 6. 事件处理
const handleTreeCheck: TreeProps['onCheck'] = (checkedKeysValue:any, _: any, { onItemSelect }: any) => {
  // 处理checkedKeys的两种可能类型
  const checked: Key[] = Array.isArray(checkedKeysValue)
    ? checkedKeysValue
    : checkedKeysValue 
      ? [...checkedKeysValue.checked, ...checkedKeysValue.halfChecked]
      : [];

  // 过滤叶子节点并转换为string
  const leafKeys: string[] = checked
    .map(key => String(key))
    .filter(key => {
      const node = findNodeInTree(treeData, key);
      return node?.isLeaf === true;
    });

  checkedKeys.value = leafKeys;

  // 同步到transfer组件
  if (onItemSelect) {
    flattenedData.value.forEach(item => {
      const key = item.key as string;
      onItemSelect(key, leafKeys.includes(key));
    });
  }
};

const handleTransferChange = (newTargetKeys: string[]) => {
  targetKeys.value = newTargetKeys;
  checkedKeys.value = checkedKeys.value.filter(key => !newTargetKeys.includes(key));
};

const handleDragEnd = () => {};

// 7. 工具函数
const getDisplayText = (key: string): string => {
  const node = findNodeInTree(treeData, key);
  if (!node) return `未知节点(${key})`;
  
  if (node.parentKey) {
    const parentNode = findNodeInTree(treeData, node.parentKey);
    if (parentNode) {
      return `${parentNode.title}/${node.title}`;
    }
  }
  
  return node.title;
};

const findNodeInTree = (nodes: TreeNode[], key: string): TreeNode | undefined => {
  for (const node of nodes) {
    if (node.key === key) return node;
    if (node.children?.length) {
      const found = findNodeInTree(node.children, key);
      if (found) return found;
    }
  }
  return undefined;
};

const handleButtonClick = (currentKey: string) => {
  const currentIndex = sortedTargetKeys.value.indexOf(currentKey);
  if (currentIndex === -1) return;
  
  const currentState = buttonStates.value[currentKey] ?? false;
  
  if (!currentState) {
    sortedTargetKeys.value.forEach((key, index) => {
      buttonStates.value[key] = index <= currentIndex;
    });
  } else {
    buttonStates.value[currentKey] = false;
    sortedTargetKeys.value.forEach((key, index) => {
      if (index > currentIndex) {
        buttonStates.value[key] = false;
      }
    });
  }
};

// 8. 初始化
watch(targetKeys, (newKeys) => {
  newKeys.forEach(key => {
    if (!(key in buttonStates.value)) {
      buttonStates.value[key] = false;
    }
  });
}, { immediate: true });
</script>

<style scoped>
.tree-transfer-container {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

.right-panel {
  width: 100%;
  height: 100%;
  overflow: auto;
  padding: 8px 0;
}

.right-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  margin: 2px 0;
  border-radius: 4px;
  cursor: pointer;
}

.right-item:hover {
  background-color: #f5f5f5;
}

.item-content {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.ant-transfer-list-header) {
  display: none;
}

:deep(.ant-tree) {
  padding: 8px;
}
</style>